#include "mystdio.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

void mfile_init(mfile* f, int fd)
{
    f->fd = fd;
    f->cap = MAXBUFSIZE*4/5;
    f->size = 0;
    memset(f->buf, 0, MAXBUFSIZE);
}


mfile* mopen(const char* file, const char* mode)
{   
    int fd = -1;
    if(mode[0] == 'r')
    {
        fd = open(file, O_RDONLY | O_CREAT, 0666);
    }
    else if(mode[0] == 'w')
    {
        fd = open(file, O_WRONLY | O_CREAT, 0666);
    }
    else if(mode[0] == 'a')
    {
        fd = open(file, O_WRONLY | O_CREAT | O_APPEND, 0666);
    }
    if (fd < 0)
    {
        return NULL;
    }
    mfile* f = (mfile*)malloc(sizeof(mfile));
    mfile_init(f, fd);
    return f;
}



size_t mwrite(mfile* f, const char* buf, int len)
{
    memcpy(f->buf + f->size, buf, len);
    f->size += len;
    if(f->size >= f->cap)
    {
        mfflush(f);
    }
    return len;
}


int mfflush(mfile* f)
{
    if(f->size > 0)
    {
        int ret = write(f->fd, f->buf, f->size);
        if(ret < 0)
        {
            return -1;
        }
        f->size = 0;

    }
    return 0;
}


int mflose(mfile* f)
{
    mfflush(f);
    close(f->fd);
    free(f);
    return 0;
}